<?php defined('SYSPATH') or die('No direct script access.');

/**
 *Copyright www.stourweb.com
 *Author: lh
 *Desc: 对外回调模块
 */
class Controller_Pc_Api_V2_Callback extends Controller
{
    public function before()
    {
        parent::before();
    }
    
    /**
     * 物流订阅回调
     */
    public function action_getExpressCallback()
    {
        //兼容写法
        if (empty($_POST))
        {
            $_POST = file_get_contents('php://input');
        }
        if( is_array($_POST) ){
            // DB::insert('express_info', array_keys(array('text'=>$_POST['param'])))->values(array('text'=>$_POST['param']))->execute();
            $params = json_decode($_POST['param'], true);
            if( is_array($params) && isset($params['status']) && isset($params['lastResult']) && isset($params['lastResult']['nu']) ){
                $data['express_sn'] = $params['lastResult']['nu'];
                if( DB::select()->from('express_info')->where('express_sn', '=', $data['express_sn'])->execute()->current() ){
                    //已存在数据，加入最新的数据
                    if( $params['comNew'] && $params['comOld'] != $params['comNew'] ){
                        $data['com_old'] = $params['comNew'];
                        $data['com_new'] = $params['comNew'];
                    }
                    $data['context'] = json_encode($params['lastResult']['data']);
                    $data['text'] = json_encode($params);
                    DB::update('express_info')->set($data)->where('express_sn', '=', $data['express_sn'])->execute();
                    echo json_encode(array('result'=>true, 'returnCode'=>200, 'message'=>'成功'));exit;
                }else{
                    //第一次接收推送
                    $data['status'] = $params['status'];
                    $data['message'] = $params['message'];
                    $data['com_old'] = isset($params['comNew'])&&isset($params['comOld'])&&$params['comNew']!=$params['comOld']?$params['comNew']:(isset($params['comOld'])?$params['comOld']:'');
                    $data['com_new'] = isset($params['comNew'])?$params['comNew']:'';
                    $data['state'] = $params['lastResult']['state'];
                    $data['ischeck'] = $params['lastResult']['ischeck'];
                    $data['context'] = json_encode($params['lastResult']['data']);
                    $data['text'] = json_encode($params);
                    $data['add_time'] = date('Y-m-d H:i:s');
                    list($re,$row) = DB::insert('express_info', array_keys($data))->values($data)->execute();
                    if( $re ){
                        echo json_encode(array('result'=>true, 'returnCode'=>200, 'message'=>'成功'));exit;
                    }
                }
            }
        }
    }
}
